package com.mindframe.advreader;

import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserFactory;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.Toast;


public class MainActivity extends Activity {
	
	ListView listView;
	private static String urlRSS;
	ArrayList<ADV> advs;
	ADVAdapter advAdapter;
	Context context;
	TareaDescarga tarea;
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        urlRSS = "http://feeds.feedburner.com/AscoDeVida?format=xml";
        advs = new ArrayList<ADV>();
       
        
        
        listView = (ListView)findViewById(R.id.listView1);
        listView.setAdapter(advAdapter);
        
        lanzaDescargaADV();
        
        advAdapter = new ADVAdapter(context, R.layout.fila, advs);
        
        listView.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int position, long id) {
				//ID es el número de fila seleccionado
			}
		});
        
        
    }
    
    void lanzaDescargaADV(){
    	try{
    		tarea = new TareaDescarga();
    		tarea.execute(new URL(urlRSS));
    		
    	}catch (MalformedURLException e){
    		e.printStackTrace();
    	}
    }
    //ejecutará la descarga en segundo plano:
    private class TareaDescarga extends AsyncTask<URL, String, List<ADV>>{
    	ArrayList<ADV> advDescargados;
    	ProgressDialog progressDialog;
    	boolean error = false;
		@Override
		protected List<ADV> doInBackground(URL... params) {
			try{
				URL url = params[0];
				advDescargados = new ArrayList<ADV>();
				
				XmlPullParserFactory parserCreator = XmlPullParserFactory.newInstance();
				XmlPullParser parser = parserCreator.newPullParser();
				parser.setInput(url.openStream(), "UTF-8");
				
				int parserEvent = parser.getEventType();
				
				boolean insideTag = false;
				
				while(parserEvent != XmlPullParser.END_DOCUMENT){
					String tag = parser.getName();
					
					if(parserEvent == XmlPullParser.START_TAG){
						if(tag.equalsIgnoreCase("item")){
							insideTag = true;
							
						}else if(tag.equalsIgnoreCase("title")){
							if(insideTag){
								Log.d("titulo", parser.nextText());
							}
						}else if(tag.equalsIgnoreCase("description")){
							if(insideTag){
								Log.d("descripcion", parser.nextText());
							}
						}
						
					}else if(parserEvent == XmlPullParser.END_DOCUMENT && tag.equalsIgnoreCase("item")){
						insideTag = false;
					}
					
					parserEvent = parser.next();
				}
				
				
			}catch (Exception e){
				Log.e("error", e.getMessage());
				error = true;
			}
			
			
			return advDescargados;
		}

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			if(advAdapter != null)
				advAdapter.clear();
			
			progressDialog = ProgressDialog.show(MainActivity.this, "Espere...", "Descargando ADV", true, true);
			
			progressDialog.setOnCancelListener(new OnCancelListener() {
				
				@Override
				public void onCancel(DialogInterface dialog) {
					tarea.cancel(true);
				}
			});
			
			
		}

		@Override
		protected void onCancelled() {
			super.onCancelled();
			advAdapter.clear();
			advDescargados = new ArrayList<ADV>();
		}

		@Override
		protected void onProgressUpdate(String... progreso) {
			super.onProgressUpdate(progreso);
			progressDialog.setMessage(progreso[0]);
			advAdapter.notifyDataSetChanged();
		}

		@Override
		protected void onPostExecute(List<ADV> result) {
			super.onPostExecute(result);
			
			for(ADV adv:advDescargados){
				advAdapter.add(adv);
			}
			
			advAdapter.notifyDataSetChanged();
			progressDialog.dismiss();
			if(error){
				Toast.makeText(context, "Se ha producido un error", Toast.LENGTH_LONG).show();
			}
		}

    	
    }
    
}
